#include "log.hpp"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <strings.h>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

class Udpclient
{
private:
    uint16_t _port;
    string _ip;

    uint32_t _sockfd;
    bool _running = false;

public:
    Udpclient(string ip, uint16_t port)
        : _ip(ip), _port(port){};

    void init_start()
    {
        // 1. 创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            cerr << "socket create fail" << endl;
            exit(2);
        }
        cout << "socket create sucess" << " socketfd = " << _sockfd << endl;

        // 2. 不需要用户自己绑定socket和网络信息，OS会自动绑定
        // 客户端构建目标主机信息

        struct sockaddr_in goal;
        bzero(&goal, 0);
        goal.sin_family = AF_INET;
        goal.sin_addr.s_addr = inet_addr(_ip.c_str());
        goal.sin_port = htons(_port); // port主机序列转网络序列

        string str;
        while (true)
        {
            cout << "Please Enter# ";        
            getline(cin, str);

            //将消息发送给服务端
            sendto(_sockfd, str.c_str(), str.size(), 0, (struct sockaddr *)&goal, sizeof(goal));

            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            char buffer[1024];
            //接收来自服务端的消息
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "server echo# " << buffer << std::endl;
            }
        }
    }

    ~Udpclient()
    {
    }
};
